<template>
  <div class="index">
    <!-- 引用封装的顶部导航栏组件 -->
    <HomeHeader
      :showSerch="showSearch"
      :login="user"
      @user="handleUser"
      ref="HomeHeader"
    >
    </HomeHeader>
    <main>
      <!-- 设置二级路由 -->
      <router-view></router-view>
    </main>

    <!-- 注册/登录对话框 -->
    <el-dialog
      title="Share"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
      class="login-form"
    >
      <el-input placeholder="请输入用户名" v-model="loginForm.username">
        <template slot="prepend">用户名</template>
      </el-input>
      <el-input
        show-password
        placeholder="请输入密码"
        v-model="loginForm.password"
      >
        <template slot="prepend">密&nbsp;&nbsp;码</template>
      </el-input>
      <el-input
        v-show="isSignIn"
        placeholder="请输入邮箱"
        v-model="loginForm.email"
      >
        <template slot="prepend">邮&nbsp;&nbsp;箱</template>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLogin">取 消</el-button>
        <el-button type="primary" @click="login">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updateDialogVisible"
      width="30%"
      center
    >
      <!-- 头像上传与回显 -->
      <el-upload
        style="display: flex; justify-content: center"
        name="avatar"
        action="http://localhost:3000/upload/avatar/"
        :show-file-list="true"
        :limit="1"
        :on-exceed="handleImageExeed"
        :before-upload="beforeImageUpload"
        :on-success="handleSuccessUpload"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          style="width: 60px; height: 60px; border-radius: 50px"
        />
        <i v-else class="uploader-tip">点击修改头像</i>
      </el-upload>
      <el-input
        placeholder="请输入用户名"
        disabled
        v-model="updateForm.username"
      >
        <template slot="prepend">用户名</template>
      </el-input>
      <el-input placeholder="请输入昵称" v-model="updateForm.nickname">
        <template slot="prepend">昵&nbsp;&nbsp;称</template>
      </el-input>
      <el-input placeholder="请输入邮箱" v-model="updateForm.email">
        <template slot="prepend">邮&nbsp;&nbsp;箱</template>
      </el-input>
      <el-input placeholder="请输入个性签名" v-model="updateForm.signature">
        <template slot="prepend">签&nbsp;&nbsp;名</template>
      </el-input>
      <el-input
        placeholder="请输入密码"
        v-model="updateForm.password"
        show-password
      >
        <template slot="prepend">密&nbsp;&nbsp;码</template>
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdate">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 返回顶部和评价 -->
    <div class="back-top" :class="backTopShow ? '' : 'hide'">
      <div>
        <img
          src="@/assets/images/mark.png"
          alt=""
          @click="showEvaluate = !showEvaluate"
        />
      </div>
      <div class="evaluate" v-if="showEvaluate">
        <p style="margin-bottom: 10px; margin-left: -5px">
          请对我的小站进行评价
        </p>
        <el-rate
          v-model="evaluateContent.mark"
          :colors="colors"
          @change="evaluateChange"
        >
        </el-rate>
      </div>
      <img
        src="@/assets/images/backTop.png"
        alt=""
        @click="backTop"
        style="margin-top: 15px"
      />
    </div>

    <!-- 引用封装的页脚组件 -->
    <home-footer beiAn="" class="footer">
      <template #device
        >A clever person solves a problem. A wise person avoids it</template
      >
    </home-footer>
  </div>
</template>

<script>
// 导入组件
import HomeHeader from "@/components/headerNew.vue";
import HomeFooter from "@/components/footerNew.vue";

export default {
  name: "HomeView",
  components: {
    HomeHeader,
    HomeFooter,
  },
  data() {
    return {
      backTopShow: false,

      // 与header组件通信

      showSearch: true,

      theme: {
        show: true,
      },

      user: {
        show: true,
        describe: [
          { id: "nickname", name: "尚未登录哟~" },
          { id: "signIn", name: "注册" },
          { id: "login", name: "登录" },
          { id: "modify", name: "修改资料" },
          { id: "signOut", name: "退出" },
        ],
      },
      // 用户登陆注册配置
      // 登陆注册对话框显示与否
      centerDialogVisible: false,
      // 修改用户信息对话框显示与否
      updateDialogVisible: false,
      // 登陆注册表单
      loginForm: {
        username: "",
        password: "",
        email: "",
      },
      // 修改用户信息表单
      updateForm: {
        avatar: "",
        username: "",
        password: "",
        email: "",
        nickname: "",
        signature: "",
      },
      // 是注册还是登录
      isSignIn: false,
      imageUrl: true,

      // 评价
      showEvaluate: false,
      evaluateContent: { user_id: null, mark: null },

      colors: ["#99A9BF", "#F7BA2A", "#FF9900"], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
    };
  },
  created() {
    // 监听滚动事件
    window.addEventListener("scroll", this.handleScroll, true);
    // 获取职位列表
    this.getLoginUser();
    this.getUserInfo();
  },
  destroyed() {
    //离开这个界面后，清除监听事件
    window.removeEventListener("scroll", this.handleScroll);
  },

  mounted() {
    this.getHighlightIndex();
  },
  methods: {
    //滚动事件
    handleScroll() {
      //判断滚动条是否位于顶部, 是返回true, 否返回false
      if (document.documentElement.scrollTop > 200) {
        this.backTopShow = true;
      } else {
        this.backTopShow = false;
      }
    },

    // 根据token获取已登录用户的信息
    getLoginUser() {
      // GET /login/getinfo
      this.$http.get("/login/getinfo").then((res) => {
        const { code, msg, result } = res;
        // token合法: 用户已登录
        if (code == 0) {
          this.user.describe = [
            { id: "nickname", name: "尚未登录哟~" },
            { id: "modify", name: "修改资料" },
            { id: "signOut", name: "退出" },
          ];
          // this.user.img = 'yl.jpg'
          this.user.img = result.avatar;
          this.user.describe[0].name = result.nickname;
          this.updateForm.username = result.username;
          this.updateForm.nickname = result.nickname;
          this.updateForm.signature = result.signature;
          this.updateForm.email = result.email;
          this.updateForm.password = result.password;
          this.updateForm.avatar = result.avatar;
          this.imageUrl =
            result.avatar.indexOf("/download/avatar") == -1
              ? "default/tx-user.svg"
              : result.avatar;
          return;
        }
        // token 不合法 (如 : 过期, 伪造)
        else if (code == 401) {
          localStorage.removeItem("token");
          this.user.img = "headImg2.png";
        }
        // 其它: 如 未登录
        else {
          this.user.img = "headImg2.png";
          this.user.describe[0].name = "尚未登陆哟~";
        }
        this.user.describe = [
          { id: "signIn", name: "注册" },
          { id: "login", name: "登录" },
        ];
      });
    },

    // 获取登录用户信息
    getUserInfo() {
      // GET /login/getinfo
      this.$http.get(`/login/getinfo`).then((res) => {
        const { code, msg, result } = res;
        if (code == 0) {
          this.evaluateContent.user_id = result.id;
        } else {
          this.userId = "";
        }
      });
    },

    //返回顶部
    backTop() {
      document.documentElement.scrollIntoView({
        block: "start",
        behavior: "smooth", // 平滑滚动
      });
    },

    // 主导航头像下拉列表对应按钮的点击事件
    handleUser(i) {
      // 登录
      if (i == "login") {
        this.isSignIn = false;
        this.centerDialogVisible = true;
      }
      // 注册
      else if (i == "signIn") {
        this.isSignIn = true;
        this.centerDialogVisible = true;
      }
      // 修改用户信息
      else if (i == "modify") {
        this.updateDialogVisible = true;
        this.$message({
          showClose: true,
          message: "修改资料",
        });
      }
      // 退出
      else if (i == "signOut") {
        localStorage.removeItem("token");
        this.getLoginUser();
        this.$message({
          showClose: true,
          message: "已登出",
        });
      }
    },

    // 提交登录注册表单
    login() {
      // 登录
      if (!this.isSignIn) {
        // this.$refs['form'].validate((valid) => {
        //   if (valid) {
        this.$http.post(`/login`, this.loginForm).then((res) => {
          if (res.token) {
            localStorage.setItem("token", res.token);
            this.getLoginUser();
            this.$message({
              type: "success",
              message: "登录成功!",
              showClose: true,
              duration: 1500,
            });
            this.loginForm.username = "";
            this.loginForm.password = "";
            this.loginForm.email = "";
            this.getHighlightIndex();
            this.$router.push("recommend");
          } else {
            this.$message({
              type: "error",
              message: "账号或者密码不正确,请重新输入!",
              showClose: true,
              duration: 1500,
            });
          }
          //     })
          // } else {
          //   return false
          // }
        });
      }
      // 注册
      else {
        // this.$refs['form'].validate((valid) => {
        //   if (valid) {
        this.$http.post(`/users`, this.loginForm).then((res) => {
          const { code, msg, result } = res;
          if (code == 0) {
            this.$message({
              type: "success",
              message: "注册成功, 可以登录啦!",
              showClose: true,
              duration: 1500,
            });
            this.loginForm.username = "";
            this.loginForm.password = "";
            this.loginForm.email = "";
          } else if (code == 1) {
            this.$message({
              type: "error",
              message: "注册失败, 请换个用户名试试!",
              showClose: true,
              duration: 1500,
            });
          } else {
            this.$message({
              type: "error",
              message: "其它失败原因!",
              showClose: true,
              duration: 1500,
            });
          }
        });
      }
      this.centerDialogVisible = false;
    },

    // 取消登录注册
    cancelLogin() {
      this.loginForm.username = "";
      this.loginForm.password = "";
      this.loginForm.email = "";
      this.centerDialogVisible = false;
      this.$message({
        showClose: true,
        message: "取消登录注册",
      });
    },

    // 修改用户信息
    update() {
      this.$http
        .put(`/users/${this.updateForm.username}`, this.updateForm)
        .then((res) => {
          const { code, msg, result } = res;
          if (code == 0) {
            this.getLoginUser();
            this.$message({
              type: "success",
              message: "修改成功!",
              showClose: true,
              duration: 1500,
            });
          } else {
            this.$message({
              type: "error",
              message: "修改失败!",
              showClose: true,
              duration: 1500,
            });
          }
        });
      this.updateDialogVisible = false;
    },

    // 取消修改用户信息
    cancelUpdate() {
      this.updateDialogVisible = false;
      this.$message({
        showClose: true,
        message: "取消修改用户信息",
      });
    },
    // 图片上传处理函数
    handleSuccessUpload(res, file, fileList) {
      this.imageUrl = res.result.path;
      this.updateForm.avatar = res.result.path;
    },
    // 约束上传图片的数量
    handleImageExeed(files, fileList) {
      if (files.length === 1) {
        this.$message.error("只能上传一张图片");
      }
    },
    // 约束上传图片类型与大小
    beforeImageUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (
        [
          "image/jpeg",
          "image/svg",
          "image/gif",
          "image/jpg",
          "image/png",
        ].indexOf(file.type) === -1
      ) {
        this.$message.error(
          "上传头像图片只能是 JPG , PNG , JPEG, svg, gif 格式!"
        );
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
        return false;
      }
    },

    //得到当前高亮菜单的index
    getHighlightIndex() {
      this.$refs.HomeHeader.current = "/recommend";
    },

    //评分
    evaluateChange() {
      let evaluateContent = this.evaluateContent;
      this.$http.post("/evaluate", evaluateContent).then((res) => {
        if (res.code == 0) {
          this.evaluateContent = { user_id: null, mark: null };
          this.$message({
            message: "感谢评价",
            type: "success",
          });
          this.showEvaluate = false;
        } else {
          this.$message({
            message: "评价失败",
            type: "warn",
          });
        }
      });
    },
  },
};
</script>

<style lang="less">
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Rancho&display=swap");
@import "~styles/theme.styl";
@import "~styles/mixins.styl";

.banner-img {
  width: 80%;
  margin-top: 100px;
  margin-left: 200px;
}

.fade {
  -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
  filter: grayscale(100%);
}

.index {
  /* 自定义css变量 */
  --header-height: 60px;
  --footer-height: 136px;
  display: flex;
  flex-direction: column;
  transition: all 0.5s ease !important;
  // 使用css变量, 在js中修改css变量值实现昼夜切换
  background: var(--background);
  color: var(--color);

  main {
    background-color: #f5f7fa;
    min-height: calc(100vh - var(--footer-height));
  }

  .back-top {
    position: relative;
    top: 750px;
    cursor: pointer;
    position: fixed;
    right: -50px;
    transition: all 0.5s ease-in-out;
    animation: float 2s linear infinite;
    z-index: 999;

    &.hide {
      top: -900px;
    }

    img {
      width: 25%;
    }

    .evaluate {
      position: absolute;
      top: 15px;
      left: -137px;
      color: white;
      font-size: 12px;
    }
  }

  .login-form {
    font-family: "Rancho", cursive;
    font-size: 50px;
  }

  .el-dialog .el-input {
    margin-top: 10px;
  }
}

@keyframes float {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-6px);
  }

  100% {
    transform: translateY(0);
  }
}

.el-dialog__title {
  font-size: 20px;
}
</style>
